﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using BMUpload.Utility;
using System.Xml;
using System.Windows.Forms;
namespace BMUpload
{   //上传业务类
    public  class UploadBLL
    {

        public bool Login(string UserID, string Pwd)
        {
            bool LoginOK;
            string sss = @"<?xml version=""1.0"" encoding=""utf-8""?><hnisi>
                        <head><version>1.0</version></head><body><params>
                        <param key=""USERID"" val=""{0}""/>
                        <param key=""PASSWORD"" val=""{1}"" />
                        </params></body></hnisi>";
            string endpoint = CurrentUser.Instance.EndpointName; //"CommFileServiceHttpSoap11Endpoint";
            sss = string.Format(sss, UserID, Pwd); 

            #region 另一种构造方式
            //BasicHttpBinding tc = new BasicHttpBinding();
            //tc.TransferMode = TransferMode.Streamed;
            //tc.MessageEncoding = WSMessageEncoding.Mtom;
            #endregion
            ServiceR.CommFileServicePortTypeClient scr = new ServiceR.CommFileServicePortTypeClient(endpoint);
            
            try
            {
                string srv = scr.login("XML", "XMLPROCESSOR", "FN1", sss);
                string suc1 = string.Empty;
                analysisRV arv = new analysisRV(srv);
                arv.Deal();
                if (arv.FHZ.Equals("-1"))
                {
                    throw new Exception("错误信息:" + ErrCodeToString(arv.ERRCode)); 
                }
                else
                {
                    CurrentUser.Instance.SessionID = arv.SESSIONID;
                    CurrentUser.Instance.UserID = UserID;
                    LoginOK = true;
                }
                
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgBox("登录出现错误:" + ex.Message); 
                LoginOK = false; 
            }


            return  LoginOK ;
        }

        public DataTable getUsers()
        {
            string Strsql = string.Empty;

            Strsql = "SELECT USERID,PWD FROM info_user ";
            try
            {
                DbHelperSQLP xccn = new DbHelperSQLP();
                return xccn.Query(Strsql).Tables[0];
            }
            catch (Exception ex)
            {
                //return null;
                throw ex;
            }
        }

        public  bool saveUser(string userid, string pwd)
        {
            string strsql =string.Format( " SP_SaveUser '{0}','{1}' ",userid,pwd);
            try
            {
                DbHelperSQLP xccn = new DbHelperSQLP();
                xccn.ExecuteSql(strsql) ;
                return true;
            }
            catch (Exception ex)
            {
                //return null;
                throw ex;
            }
        }
        /// <summary>
        /// 根据条件查询数据
        /// </summary>
        /// <param name="xtype"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public DataSet SearchData(string xtype,UploadArgs e)
        {
            string Strsql = string.Empty;

            Strsql = "Sp_" + xtype + " '{0}','{1}',{2},'{3}' ";
            Strsql = string.Format(Strsql, e.BeginDate, e.EndDate, Common.ConverttoInt(  e.SearchHIS), e.DocumentID);
            try
            {
                DbHelperSQLP xccn = new DbHelperSQLP();
                return xccn.Query(Strsql);
            }
            catch (Exception ex)
            {
                SysLog.WriteLocalErrLog(Strsql);
                SysLog.WriteLocalErrLog(ex.Message); 
                return null;
                //throw ex;

            }
        }

        public DataTable GetSendHIS (string xtype,UploadArgs e)
        {
            string Strsql = string.Empty;

            Strsql = "Sp_SendHIS '{0}' ";
            Strsql = string.Format(Strsql, xtype +"_HIS");
            try
            {
                DbHelperSQLP xccn = new DbHelperSQLP();
                return xccn.Query(Strsql).Tables[0];
            }
            catch (Exception ex)
            {
                //return null;
                throw ex;
            }
        }



        public string  LookResult(string docID)
        {
            string strresult;
            //1判断是否登录成功
            if (string.IsNullOrWhiteSpace(CurrentUser.Instance.SessionID))
            {
                FrmLogin fr = new FrmLogin();
                fr.ShowDialog();
            }
            if (string.IsNullOrWhiteSpace(CurrentUser.Instance.SessionID))
            {
                throw new Exception("未正常登录，查询失败！");
            }

            string sss = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                        <hnisi><body><params><param key=""SJLX"" val=""check_uploadState"" />
                        <param key=""DOCUMENTID"" val=""{0}""/>
                        </params><datasets><dataset>
                        <DOCUMENTID>{0}</DOCUMENTID></dataset></datasets></body></hnisi>";
            string endpoint = CurrentUser.Instance.EndpointName; //"CommFileServiceHttpSoap11Endpoint";
            sss = string.Format(sss, docID);
            ServiceR.CommFileServicePortTypeClient scr = new ServiceR.CommFileServicePortTypeClient(endpoint);
            try
            {
                string loginxml = BuiltSendLoginXMl();
                string srv = scr.process("XML", "XMLPROCESSOR", "FN1", loginxml, Encoding.UTF8.GetBytes(sss));
                analysisRV arv = new analysisRV(srv);
                arv.Deal();
                SysLog.WriteLocalLog(srv);
                strresult = arv.MSG;
                //if (arv.FHZ.Equals("-1"))
                //{
                //    throw new Exception("错误信息:" + ErrCodeToString(arv.ERRCode));
                //}
            }
            catch (Exception ex)
            {
                //MsgHelper.ShowErrorMsgBox("登录出现错误:" + ex.Message);
                strresult ="查询失败：" + ex.Message;
            }
            return strresult;
        }


        public string getGridCap(string xtype)
        {
            string caplist = string.Empty;
            caplist = AppSettings.GetValue(xtype + "_Cap");
            return caplist;
            #region 以前的写法，现在将标题配置在配置文件中
            switch (xtype)
            { 
                case "ltqyJhEntry":
                    //caplist = "原销售单号/进货单号/进货日期/供货企业名称/供货企业许可证编号/产品条形码/生产批次/数量/生产日期/计量单位";
                    break;
                case "ltqyJhmx_XmEntry":
                    //caplist = "进货单号/产品条形码/生产批次/箱码/追溯码";
                    break;
                case "ltqyXsEntry":
                    caplist = "销售单号/销售日期/购货企业名称/购货企业许可证编号/产品条形码/生产批次/生产日期/数量/计量单位";
                    break;
                case "lsqyXsEntry":
                    caplist = "销售单号/销售日期/购买人/产品条形码/生产批次/生产日期/数量/计量单位";
                    break;
                case "ltqyXsmx_XmEntry":
                    caplist = "销售单号/产品条形码/生产批次/箱码/追溯码";
                    break;
                case "ltqyThEntry":
                    caplist = "退货单号/退货日期/供货企业名称/供货企业许可证编号/产品条形码/生产批次/生产日期/数量/计量单位";
                    break;
                case "ltqyThmxXm_XmEntry":
                    caplist = "退货单号/产品条形码/生产批次/箱码/追溯码";
                    break;
            }
            #endregion


        }
        /// <summary>
        /// 上传数据
        /// </summary>
        /// <param name="upds"></param>
        /// <returns></returns>
        public string UploadData(DataTable updt, string SJLX,string docid="")
        { 
            //1判断是否登录成功
            if (string.IsNullOrWhiteSpace( CurrentUser.Instance.SessionID))
            {
                FrmLogin fr = new FrmLogin();
                fr.ShowDialog();
            }
             if (string.IsNullOrWhiteSpace( CurrentUser.Instance.SessionID))
            {
                 throw new Exception("未正常登录，上传失败！");
            }
            //获取上传编码
            DbHelperSQLP mycn=new DbHelperSQLP ();
            string DOCUMENTID = "";
            if (string.IsNullOrWhiteSpace(docid))
            {
                DOCUMENTID=mycn.GetSingle("EXEC SP_GETXNO ").ToString();
            }
            else
            { DOCUMENTID = docid; }
            //由于是增加了网格数据，所以需要将传进来的DataSet做一下处理

            
            DataTable Senddt = DealDataTable(updt, SJLX);

            //拼XML
            string sendxml = BuiltSendXML(Senddt, SJLX, DOCUMENTID);
            string loginxml = BuiltSendLoginXMl();

            string rvmsg = string.Empty;
            #region 上传
            try
            {
                string endpoint = CurrentUser.Instance.EndpointName; 
                ServiceR.CommFileServicePortTypeClient scr = new ServiceR.CommFileServicePortTypeClient(endpoint);
                string  srv = scr.process("XML", "XMLPROCESSOR", "FN1", loginxml, Encoding.UTF8.GetBytes(sendxml));
                analysisRV arv = new analysisRV(srv);
                arv.Deal();
                SysLog.WriteLocalLog(srv); 
                if (arv.FHZ.Equals("-1"))
                {
                    throw new Exception("错误信息:" + ErrCodeToString(arv.ERRCode));
                }
                else
                {
                    BackToHis(updt, SJLX, DOCUMENTID); 
                }
            }
            catch (Exception ex)
            {
                rvmsg = ex.Message;
            }

            #endregion

            return rvmsg ;
        }

        /// <summary>
        /// 备份数据到历史表
        /// </summary>
        /// <param name="updt"></param>
        /// <param name="SJLX"></param>
        /// <param name="documentid"></param>
        /// <returns></returns>
        public void BackToHis(DataTable updt, string SJLX, string documentid)
        {
            try
            {
                updt.Columns.Add("DOCUMENTID", Type.GetType("System.String"));
                updt.Columns.Add("SENDTIME", Type.GetType("System.DateTime"));

                //for (int i = 0; i < updt.Rows.Count; i++)
                //{
                //    updt.Rows[i]["DOCUMENTID"] = documentid;
                //    updt.Rows[i]["SENDTIME"] = DateTime.Now ;

                //}
                DbHelperSQLP mycn = new DbHelperSQLP();
                mycn.ExecuteSql("DELETE FROM " + SJLX + "_HIS WHERE DOCUMENTID='" + documentid + "'"); 
                mycn.SaveDT(updt, SJLX +"_HIS");
                if (SJLX.Equals("scqyCpjysmEntry"))
                {
                    mycn.ExecuteSql("DELETE FROM " + SJLX + "_HIS WHERE DOCUMENTID='" + documentid + "' AND FILE_CONTENT=''"); 
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool CheckDataTable(DataTable dt)
        { 
            foreach (DataRow objdr in dt.Rows)
            {
                if (string.IsNullOrWhiteSpace(objdr["XM"].ToString()) && string.IsNullOrWhiteSpace(objdr["ZSM"].ToString()))
                {
                    objdr.SetColumnError("XM", "追溯码和箱码两者必填一个！");
                    objdr.SetColumnError("ZSM", "追溯码和箱码两者必填一个！");
                    return false;
                }                
            }


            return true;
        }

        public void SetCorpInfo()
        {
            string val = AppSettings.GetValue("CorpInfo");
            string val2 = AppSettings.GetValue("SharePath");
            FrmInfo frm = new FrmInfo(val,val2);
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                AppSettings.SetValue("CorpInfo", frm.CompanyName);
                AppSettings.SetValue("SharePath", frm.Sharepath);
                MsgHelper.ShowInformationMsgBox("设置成功！"); 
            }
        }
        #region 私有方法
        private   string BuiltSendXML(DataTable  updt, string SJLX,string documentid )
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);

            XmlElement root = doc.CreateElement("hnisi");
            doc.AppendChild(root);
            XmlElement body = doc.CreateElement("body");
            root.AppendChild(body);



            #region 添加参数
            XmlElement datasets = doc.CreateElement("params");
            body.AppendChild(datasets);

            XmlElement para = doc.CreateElement("param");
            para.SetAttribute("key", "SJLX");
            para.SetAttribute("val", SJLX);
            datasets.AppendChild(para);

            para = doc.CreateElement("param");
            para.SetAttribute("key", "DOCUMENTID");
            para.SetAttribute("val", documentid);
            datasets.AppendChild(para);
            #endregion

            #region 添加数据
            datasets = doc.CreateElement("datasets");
            body.AppendChild(datasets);

            foreach (DataRow dr in updt.Rows)
            {
                XmlElement ds = doc.CreateElement("dataset");
                datasets.AppendChild(ds);
                foreach (DataColumn dc in updt.Columns)
                {
                    XmlElement detail = null;
                    //如果是成品检验报告，需要特殊处理，转换成BASE64
                    if (SJLX.Equals("scqyCpjysmEntry") && dc.ColumnName.ToString().Equals("FILE_CONTENT"))
                    {
                        string colvalue = dr[dc.ColumnName].ToString();
                        colvalue = FileHelper.FileToBase64Code(colvalue); 
                        detail = doc.CreateElement(dc.ColumnName.ToString());
                        detail.InnerText = colvalue;
                    }
                    else
                    {
                        detail=doc.CreateElement(dc.ColumnName.ToString());
                        detail.InnerText = dr[dc.ColumnName].ToString();
                    }
                    ds.AppendChild(detail);
                }
            }

            #endregion
            doc.Save(@"d:\bb.xml"); 
            return doc.InnerXml;
        }

        private string BuiltSendLoginXMl()
        {
            string login = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                        <hnisi>
                          <head><version>1.0</version></head>
	                        <body>
		                        <params>
                               <param key=""USERID"" val=""{0}"" />
		                        <param key=""SESSIONID"" val=""{1}"" />
		                        </params>
	                        </body>
                        </hnisi>
                        ";
            login = string.Format(login, CurrentUser.Instance.UserID,CurrentUser.Instance.SessionID);
            return login;
        }
        /// <summary>
        /// 根据配置文件拼凑上传数据
        /// </summary>
        /// <param name="updt"></param>
        /// <param name="SJLX"></param>
        /// <returns></returns>
        private  DataTable DealDataTable(DataTable updt, string SJLX)
        { 
            string sendlist = string.Empty;
            sendlist = AppSettings.GetValue(SJLX + "_Send");
            if (string.IsNullOrWhiteSpace(sendlist))
            { throw new Exception("未设置上传的字段列表，请检查！"); }
            List<string> list = new List<string>(sendlist.Split('/'));
            DataTable dt2 = new DataTable();
            foreach (string t in list)
            {
                if (updt.Columns.Contains(t))
                {
                    dt2.Columns.Add(updt.Columns[t].ColumnName);
                }
                else
                {
                    throw new Exception("查询到的数据中不存在列" + t +",请检查查询语句或上传配置字段!");
                }
            }

            foreach (DataRow dr in updt.Rows)
            {
                bool begood = true;
                if (SJLX.Equals("scqyCpjysmEntry"))
                {
                    //上传检验报告，如果没有选择报告，则不加入列表
                    if (string.IsNullOrWhiteSpace(dr["FILE_CONTENT"].ToString()))
                    {
                        begood = false;
                    }
                }
                if (begood)
                {
                    dt2.ImportRow(dr);//这是加入的是第一行
                }
            }

            return dt2;
        }

        private string ErrCodeToString(string Errcode)
        {
            string errdes=string.Empty ;
            switch (Errcode)
            {   
//800	数据格式错误
//801	数据必录
//802	数据与字典不符合
//803	数据长度大于规定长度
//804	xml模版不对应
//805	XML模版 ： 数据上传类型【SJLX】获取为空或不存在【库中不存在该上传类型SJLX】
//806	会话已经结束，请重新登录
//807	用户ID获取为空
//808	文件获取失败
//809	文件解析失败!请检查文件格式是否为xml文件
//810	文件处理错误
//811	文件处理失败,无法取得上传的文件内容
//812	用户未激活，请登录广东省婴幼儿配方乳粉追溯平台进行激活
//813	登陆失败
//814	保存数据时出现错误
//815	XML模版 ：文档唯一标识号【DOCUMENTID】获取为空
//816	DOCUMENTID的值的长度超过50
//817	文件大小超过了限制大小
//818	文件数据数量跟规范不一样
//819	许可证号已过期
//840	系统错误，请联系管理员
                case "813":
                    errdes = "登陆失败";  
                    break;
                case "801":
                    errdes = "数据必录";
                    break;
                case "819":
                    errdes = "许可证号已过期";
                    break;
                case "815":
                    errdes = "XML模版 ：文档唯一标识号【DOCUMENTID】获取为空";
                    break;
                case "812":
                    errdes = "用户未激活，请登录广东省婴幼儿配方乳粉追溯平台进行激活";
                    break;
            }

            return errdes;
        }
        #endregion

    }

    public class UploadArgs
    {
        private static string _begindate = "";
        public string BeginDate { get { return _begindate; } set { _begindate = value; } }

        private static string _enddate = "";
        public string EndDate { get { return _enddate; } set { _enddate = value; } }

        private static bool _searchhis = false;
        public bool SearchHIS { get { return _searchhis; } set { _searchhis = value; } }


        private static string _documentid = "";
        public string DocumentID { get { return _documentid; } set { _documentid = value; } }
     
    }

}
